<!--
 * @Descripttion: 
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2021-06-11 11:29:18
 * @LastEditTime: 2021-06-17 12:40:57
 * @Param {**} ** **
 * @Example ***
 * @FilePath: \cscec-pms-admin\src\views\Legal\branchContract\otherTypesContract\components\ApprovalDetails.vue
-->
<template>
  <base-modal
    :footer="null"
    :title="title"
    :closable="true"
    :visible="visible"
    width="1200px"
    @cancel="handleClose"
  >
    <a-tabs
      v-model="key"
      type="card"
      class="mb20"
    >
      <a-tab-pane
        key="0"
        tab="当前流程"
      >
        <a-spin
          :spinning="flowChartLoading0"
          style="margin-bottom:10px;"
        >
          <a-empty
            v-if="flowChart[0] === ''"
            :image="simpleImage"
          />
          <img
            v-else
            style="width: 100%"
            :src="flowChart[0]"
          >
        </a-spin>
        <s-table
          ref="table0"
          bordered
          size="default"
          row-key="key"
          :columns="columns"
          :data="loadData"
          :alert="true"
          show-size-changer
          show-quick-jumper
          :show-pagination="false"
        >
          <span
            slot="serial"
            slot-scope="text, record, index"
          >{{ index + 1 }}</span>
          <template
            slot="opinions"
            slot-scope="text"
          >
            <ellipsis
              :length="30"
              tooltip
            >
              {{ text }}
            </ellipsis>
          </template>
          <template
            slot="userName"
            slot-scope="text"
          >
            <ellipsis
              :length="50"
              tooltip
              placement="right"
            >
              {{ text }}
            </ellipsis>
          </template>
        </s-table>
      </a-tab-pane>
      <a-tab-pane
        key="1"
        tab="用印流程"
      >
        <a-spin
          :spinning="flowChartLoading1"
          style="margin-bottom:10px;"
        >
          <a-empty
            v-if="flowChart[1] === ''"
            :image="simpleImage"
          />
          <img
            v-else
            style="width: 100%"
            :src="flowChart[1]"
          >
        </a-spin>
        <s-table
          ref="table1"
          bordered
          size="default"
          row-key="key"
          :columns="columns"
          :data="loadData"
          :alert="true"
          show-size-changer
          show-quick-jumper
          :show-pagination="false"
        >
          <span
            slot="serial"
            slot-scope="text, record, index"
          >{{ index + 1 }}</span>
          <template
            slot="opinions"
            slot-scope="text"
          >
            <ellipsis
              :length="30"
              tooltip
            >
              {{ text }}
            </ellipsis>
          </template>
          <template
            slot="userName"
            slot-scope="text"
          >
            <ellipsis
              :length="50"
              tooltip
              placement="right"
            >
              {{ text }}
            </ellipsis>
          </template>
        </s-table>
      </a-tab-pane>
    </a-tabs>
  </base-modal>
</template>
<script>
import { getCurrentProcess, getFlowChart } from '@/api/process'
import { getOrgEmployeesListBy, getProcessGroupPerson } from '@/api/commons'
import BaseModal from '@/components/BaseModal'
import { STable } from '@/components'
import { Ellipsis } from '@/components'
import { Empty } from 'ant-design-vue'
import JosnBig from 'json-bigint'

export default {
  name: 'ApprovalDetails',
  props: {
    title: {
      type: String,
      default: '审批详情'
    },
    visible: {
      type: Boolean,
      default: false
    },
    businessId: {
      type: String,
      default: ''
    },
    sealBusinessId: {
      type: String,
      default: ''
    }
  },
  components: {
    BaseModal,
    STable,
    Ellipsis,
    AEmpty: Empty
  },
  data() {
    return {
      key: '0',
      // 加载
      flowChartLoading0: false,
      flowChartLoading1: false,
      // 空白图片
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: 'serial',
          width: 80,
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '节点名称',
          dataIndex: 'taskName'
        },
        {
          title: '处理人',
          dataIndex: 'userName',
          scopedSlots: { customRender: 'userName' }
        },
        {
          title: '处理结果',
          dataIndex: 'processStatusName'
        },
        {
          title: '审批意见',
          dataIndex: 'opinions',
          scopedSlots: { customRender: 'opinions' },
          width: 300
        },
        {
          title: '开始时间',
          dataIndex: 'createTime'
        },
        {
          title: '滞留时间',
          dataIndex: 'durationInMillis'
        },
        {
          title: '结束时间',
          dataIndex: 'endTime'
        }
      ],
      // 流程图
      flowChart: ['', '']
    }
  },

  methods: {
    /**
     * @description: 表格数据加载方法
     * @param {Void} 
     * @return {Promise} 接口Promise
     */
    async loadData() {
      try {
        const id = this.key === '0' ? this.businessId : this.sealBusinessId
        // const { data, currentPage, totalSize } = await getCurrentProcess(id)
        return getCurrentProcess(id).then((res) => {
                    const processData = res.data
                    const userIds = []
                    const groupList = []
                    processData.forEach((item) => {
                        userIds.push(item.assignee)
                        item.userName = item.userName || ''
                        item.endTime = item.endTime || item.completed !== 2 && '进行中' || ''
                        item.durationInMillis = item.durationInMillis || item.completed !== 2 && '进行中' || ''
                        if (item.formData) {
                            try {
                                const formDataObj = JosnBig.parse(item.formData)
                                item.opinions = formDataObj.opinions
                                item.auditResult = formDataObj.reject === 'true' ? '审批不通过' : formDataObj.reject === 'false' ? '审批通过' : ''
                            } catch(e) {
                                console.error(e)
                            }

                        } else {
                            item.opinions = ''
                            item.auditResult = ''
                        }
                        // 如果groupId存在，则需要查询其节点对应的处理人；completed为1时，表示审批已完成
                        if(item.groupId && item.completed !== 1) {
                            try {
                                const groupIdObj = JosnBig.parse(item.groupId)
                                groupList.push({...groupIdObj, processTaskId: item.taskDefKey})
                            } catch(e) {
                                console.error(e)
                            }
                        }

                        item.description = []
                    })
                    // 获取后面节点的处理人列表
                    groupList.length && getProcessGroupPerson({
                        assignGroup:groupList
                    }).then(res => {
                        const targetObj = res.data || {}
                        processData.forEach(item => {
                            if(targetObj[item.taskDefKey] && item.groupId && item.completed !== 1) {
                                item.userName = targetObj[item.taskDefKey].map(item => item.name).join('、')
                            }
                        })              
                    })
                    return getOrgEmployeesListBy({ userIds, delete: true }).then((employees) => {
                        this.flowRequesting = false
                        processData.forEach((r) => {
                            employees.data.some((e) => {
                                if (e.userId === r.assignee) {
                                    r.userName = e.name
                                    return true
                                }
                            })
                        })
                        return res
                    })
                })
      } catch (error) {
        console.log(error)
        return Promise.reject(error)
      }
    },
    /**
     * @description: 获取流程图
     * @param {Void}
     * @return {Void}
     */
    getFlowChart() {
      this.flowChart = ['', '']
      this['flowChartLoading' + this.key] = true
      const id = this.key === '0' ? this.businessId : this.sealBusinessId
      getFlowChart(id)
        .then(({ status, code, data }) => {
          if (status === 200 || code === 200) {
            if (typeof data === 'string') {
              this.flowChart[this.key] = 'data:image/png;base64,' + data
            } else {
              this.flowChart[this.key] = ''
            }
          }
        })
        .finally(() => {
          this['flowChartLoading' + this.key] = false
        })
    },
    /**
     * @description: 关闭弹窗
     * @param {Void}
     * @return {Void}
     */
    handleClose() {
      this.$emit('update:visible', false)
    }
  },
  watch: {
    // 显示监听
    visible: {
      handler(newV) {
        if (newV) {
          this.$nextTick(() => {
            this.getFlowChart()
            this.$refs['table' + this.key].refresh()
          })
        }
      }
    },
    key: {
      handler(newV) {
        this.$nextTick(() => {
          this.getFlowChart()
          this.$refs['table' + newV].refresh()
        })
      }
    }
  }
}
</script>
<style lang="less" scoped>
</style>
